<template>
  <div class="p-6">
    <!-- 搜索/筛选栏 -->
    <a-space class="mb-4">
      <a-input v-model:value="filters.keyword" placeholder="搜索权限名/编码" style="width: 250px" />
      <a-select v-model:value="filters.status" placeholder="绑定接口状态" style="width: 120px" allow-clear>
        <a-select-option value="active">已绑定</a-select-option>
        <a-select-option value="disabled">未绑定</a-select-option>
      </a-select>
      <a-button type="primary" @click="fetchPermissions">搜索</a-button>
      <a-button type="dashed" @click="openAddModal">新增权限</a-button>
    </a-space>

    <!-- 批量操作 -->
    <a-space class="mb-2">
      <a-button type="dashed" danger @click="batchDelete" :disabled="!selectedPermissions.length">批量删除</a-button>
    </a-space>

    <!-- 表格 -->
    <a-table :columns="columns" :data-source="filteredPermissions" row-key="permissionId" :row-selection="rowSelection"
      bordered @row-click="openDetails" :scroll="{ x: 700 }">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 'active' ? 'green' : 'red'">
            {{ record.status === 'active' ? '已绑定' : '未绑定' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" danger @click.stop="deletePermission(record)">删除</a-button>
            <a-button type="link" @click.stop="openDetails(record)">详情</a-button>
            <a-button size="small" type="default" @click="openEditModal(record)">编辑</a-button>
          </a-space>
        </template>
        <template v-else>
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </a-table>

    <!-- 权限详情侧边栏 -->
    <a-drawer title="权限详情" :visible="showDetails" :width="360" @close="showDetails = false" placement="right">
      <div v-if="selectedPermission">
        <p><strong>权限Key：</strong> {{ selectedPermission.permissionKey }}</p>
        <p><strong>权限名称：</strong> {{ selectedPermission.permissionName }}</p>
        <p><strong>描述：</strong> {{ selectedPermission.description || '无' }}</p>

        <p><strong>状态：</strong>
          <a-tag :color="selectedPermission.status === 'active' ? 'green' : 'red'">
            {{ selectedPermission.status === 'active' ? '已绑定' : '未绑定' }}
          </a-tag>
        </p>
        <p><strong>赋予角色：</strong></p>
        <ul>
          <li v-for="r in selectedPermission.roles" :key="r">{{ r }}</li>
        </ul>
      </div>
    </a-drawer>
  </div>

  <!-- 新增/编辑权限对话框 -->
  <a-modal v-model:open="showModal" :title="isEdit ? '编辑权限' : '新增权限'" @ok="handleSave" @cancel="resetForm">
    <a-form :model="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="权限Key" required>
        <a-input v-model:value="form.permissionKey" placeholder="请输入权限Key" />
      </a-form-item>
      <a-form-item label="权限名称" required>
        <a-input v-model:value="form.permissionName" placeholder="请输入权限名称" />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="form.description" placeholder="请输入描述" />
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { strict } from 'assert'
import { Interface } from 'readline'
import { ref, computed, onMounted } from 'vue'
import { apiFetch } from '@/utils/request'
import { Modal, message } from 'ant-design-vue'
const identityurl = import.meta.env.VITE_API_IDENTITY
const permissions = ref<Permission[]>([])
const filters = ref({ keyword: '', status: '' })
const selectedPermissions = ref<string[]>([])
const showDetails = ref(false)
const selectedPermission = ref<Permission | null>(null)

interface Permission {
  permissionId: string
  permissionKey: string
  permissionName: string
  status: string,
  description: string,
  roles: string[]
}
interface ApiResponse<T> {
  isSuccess: Boolean
  errors: string[]
  data: T
}
onMounted(() => {
  fetchPermissions()
})
async function fetchPermissions() {
  const response = await apiFetch<ApiResponse<{ id: string, key: string, name: string, bindingStatus: Boolean, description: string, roles: string[] }[]>>(`${identityurl}/api/permissions`)
  permissions.value = response.data.map(a => ({
    permissionId: a.id,
    permissionKey: a.key,
    permissionName: a.name,
    status: a.bindingStatus ? 'active' : 'disabled',
    description: a.description,
    roles: a.roles
  }))
}


const columns = [

  { title: '权限编码', dataIndex: 'permissionKey', key: 'permissionKey' },
  { title: '权限名称', dataIndex: 'permissionName', key: 'permissionName' },
  { title: '权限说明', dataIndex: 'description', key: 'description' },
  { title: '绑定接口状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action' }
]

const filteredPermissions = computed(() => {
  return permissions.value.filter(p => {
    const matchKeyword = !filters.value.keyword || p.permissionName.includes(filters.value.keyword) || p.permissionKey.includes(filters.value.keyword)
    const matchStatus = !filters.value.status || p.status === filters.value.status
    return matchKeyword && matchStatus
  })
})


const rowSelection = computed(() => ({
  selectedRowKeys: selectedPermissions.value,
  onChange: (keys: string[]) => selectedPermissions.value = keys
}))


function openDetails(permission: Permission) { selectedPermission.value = permission; showDetails.value = true }
function batchDelete() { permissions.value = permissions.value.filter(p => !selectedPermissions.value.includes(p.permissionId)); selectedPermissions.value = [] }



// 对话框状态
const showModal = ref(false)
const isEdit = ref(false)
const form = ref<Permission>({
  permissionId: '',
  permissionKey: '',
  permissionName: '',
  status: 'active',
  description: '',
  roles: []
})

function openAddModal() {
  isEdit.value = false
  form.value = {
    permissionId: '',
    permissionKey: '',
    permissionName: '',
    status: 'active',
    description: '',
    roles: []
  }
  showModal.value = true
}

function openEditModal(permission: Permission) {
  isEdit.value = true
  form.value = { ...permission } // 拷贝一份数据
  showModal.value = true
}

// 保存新增或修改
async function handleSave() {
  try {
    if (isEdit.value) {
      // 修改
      const response = await apiFetch<ApiResponse<{ id: string, key: string, name: string, bindingStatus: Boolean, description: string, roles: string[] }>>(`${identityurl}/api/permissions/${form.value.permissionId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key: form.value.permissionKey, name: form.value.permissionName, description: form.value.description })
      })
      if (response.isSuccess) {
        // 本地更新那一行
        const idx = permissions.value.findIndex(
          (p) => p.permissionId === form.value.permissionId
        )
        if (idx !== -1) {
          permissions.value[idx].permissionKey=response.data.key
          permissions.value[idx].permissionName=response.data.name
          permissions.value[idx].description=response.data.description
        }
      }
    }
    else {
      // 新增
      const response = await apiFetch<ApiResponse<{ id: string, key: string, name: string, bindingStatus: Boolean, description: string, roles: string[] }>>(`${identityurl}/api/permissions`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ Id: form.value.permissionId, key: form.value.permissionKey, name: form.value.permissionName, description: form.value.description })
      })

      if (response.isSuccess && response.data) {
        // 直接 push 到列表里
        permissions.value.push({
          permissionId: response.data.id,
          permissionKey: response.data.key,
          permissionName: response.data.name,
          description: response.data.description,
          status: response.data.bindingStatus?'active':'disabled',
          roles: response.data.roles
        })
      }
    }
    showModal.value = false
  } catch (err) {
    console.error('保存权限失败', err)
  }
}


async function deletePermission(permission: Permission) {
  // 删除
  if (permission.status === 'active') {
    message.error('权限已绑定，请先解除绑定再重试')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除权限【${permission.permissionKey}】吗？此操作不可恢复！`,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await apiFetch(`${identityurl}/api/permissions/${permission.permissionId}`, {
          method: 'DELETE'
        })
        // 本地移除
        permissions.value = permissions.value.filter(p => p.permissionId !== permission.permissionId)
        message.success('删除成功')
      } catch (err) {
        console.error('删除权限失败', err)
        message.error('删除失败')
      }
    }
  })

}

// 取消时重置
function resetForm() {
  form.value = {
    permissionId: '',
    permissionKey: '',
    permissionName: '',
    status: 'active',
    description: '',
    roles: []
  }
}
</script>
